var roomList=[];
var roomsFounded = null;
var selectTurn=null;
var filterPressed;
var enmaToday=getStrToday();

function getStrToday(){
	var today = new Date();
	var dd = today.getDate();
	var mm = today.getMonth()+1;

	var yyyy = today.getFullYear();
	if(dd<10){
		dd='0'+dd;
	} 
	if(mm<10){
		mm='0'+mm;
	} 
	var strToday = dd+'/'+mm+'/'+yyyy;
	
	return strToday;
}

function doFilter() {
	var available;
	if($('input:radio[name=available]:checked').val()=="true")
		available=true;
	else
		available=false;
	
	
	var lunes = ($("#rfLunes")[0].checked)?1:null;
	var martes = ($("#rfMartes")[0].checked)?2:null;
	var miercoles = ($("#rfMiercoles")[0].checked)?3:null;
	var jueves = ($("#rfJueves")[0].checked)?4:null;
	var viernes = ($("#rfViernes")[0].checked)?5:null;
	var sabado = ($("#rfSabado")[0].checked)?6:null;
	var sDate=(getWhereAmI()==3)?$("#startDay").val():$("#startDay2").val();
	var eDate=(getWhereAmI()==3)?$("#endDay").val():$("#endDay2").val();
	
	var parameters = { 
			"MaxCapacity" : $("#maxCapacity").val(),
			"MinCapacity" : $("#minCapacity").val(),
			"StartTime" : $("#startTime").val(),
			"EndTime" : $("#endTime").val(),
			"StartDay" : sDate,
			"EndDay" : eDate,
			"RoomToFilter" : $("#roomToFilter").val(),
			"turn":$("#selectTurn").val(),
			"days":[lunes,martes,miercoles,jueves,viernes,sabado],
			"available":available,
			"whereAmI":getWhereAmI()
			};
	var schoolId=(getWhereAmI()==1)?getPlanningsRepo()[getCurrentPlannId()].schoolId:null;
	
	var filterDTO=[parameters,getWhereAmI(),schoolId];
	postJSON("/enma/home/environment/by_filter/", filterDTO, function(data) {
		//sperez: esto es porqque despues de la segunda vez no entra mas, hay que ver porque.
		//roomsFounded = data;
		
		filterRoomSuccess(data);
	});
}

function filterRoomSuccess(data) {	
	var tabla = "";
	
	if(iAmIn == 3){
		tabla += "<table class='table table-hover'><thead><tr><th>Ambiente</th><th>Capacidad</th><th>Recursos Disponibles</th><th>Edificio</th><th>Ubicaci\u00F3n</th></tr></thead><tbody>";
	}else{
		tabla += "<table class='table table-hover'><thead><tr><th>Ambiente</th><th>Capacidad</th><th>Recursos Disponibles</th><th>Edificio</th><th>Seleccionar</th></tr></thead><tbody>";
	}
	if(data){
			$("#roomsContent").html('');
			for(var i in data.environmentDTOs) {
				if(i%2 == 0) {
					trClass = "gridLightRoom";
				} else {
					trClass = "gridDarkRoom";
				}
				
				roomList[i] = data.environmentDTOs[i].description;
				var roomId = data.environmentDTOs[i].id+'Room';
				var map = data.environmentDTOs[i].location;
				if(map==''){
					map="/enma/resources/images/noImage.jpg";
				}
				//sperez: agrega los salones encontrados a la grilla
				var roomResources = "";
				for (var j=0;j<data.environmentDTOs[i].resources.length;j++){
					if(j%2==0 && j!=0){
						if(j==data.environmentDTOs[i].resources.length-1){
							roomResources = roomResources+'\n'+data.environmentDTOs[i].resources[j].description;
						}else{
							roomResources = roomResources+'\n'+data.environmentDTOs[i].resources[j].description+",";
						}
					}else{
						if(j==data.environmentDTOs[i].resources.length-1){
							roomResources = roomResources+data.environmentDTOs[i].resources[j].description;
						}else{
							roomResources = roomResources+data.environmentDTOs[i].resources[j].description+",";
						}
					}
				}
				if(iAmIn == 3){
					tabla+= "<tr><td>"+data.environmentDTOs[i].description+"</td><td>"+data.environmentDTOs[i].capacity+"</td><td>"+roomResources+"</td><td>"+data.environmentDTOs[i].building.description+"</td><td><img id='"+roomId+"' onclick='setSizeImgRoom("+"\""+roomId+"\""+")' src='"+map+"' class='imgOld'></td></tr>";
				}else{
					tabla+= "<tr><td>"+data.environmentDTOs[i].description+"</td><td>"+data.environmentDTOs[i].capacity+"</td><td>"+roomResources+"</td><td>"+data.environmentDTOs[i].building.description+"</td><td><button onclick='roomSelected("+i+");' class='selectRoomButton'></button></td></tr>";
				}
			}
			tabla+="</tbody></table>";
			$("#roomsContent").append(tabla);
	}
	var tmpStDay=$("#startDay").val();
	var tmpEndDay=$("#endDay").val();
	if(iAmIn == 3){
		initTabEnv();
		$("#startDay").val(tmpStDay);
		$("#endDay").val(tmpEndDay);
	}
	else
		getRoomFromPlanificationPhaseTwo();
}

function setSizeImgRoom(id){
	var src = $("#"+id).attr('src');
	$("#imgForShowRoom").attr('src',src);
	$("#showImgRoom").show();
}

function setSizeImgRoomBack(){
	$("#showImgRoom").hide();
}

function initTabEnv(){
	$("#roomToFilter").val("");
	$("#minCapacity").val("");
	$("#maxCapacity").val("");
	
	$("#contentRoomsPlanificationFilter").html("");
	$("#contentRoomsPlanificationGride").html("");

	$("#startDay2").hide();
	$("#startDay").show();
	$("#startDay").datepicker();
	
	$("#endDay2").hide();
	$("#endDay").show();
	$("#endDay").datepicker();
	
	$("#filterSelectDay").hide();
	$("#filterShift").hide();
	$("#filterStartDay").show();
	$("#filterEndDay").show();
	
	$("#startDay").val("");
	$("#endDay").val("");
}

function roomSelected(roomId) {
	$("#roomDescInput").val(roomList[roomId]);
	closeSelectRoomPlanification();
}

function initRoom() {
	$("#startDay").val("");
	$("#endDay").val("");
	$("#startTime").html('');
	$("#startTime").html(getTimeSelect());
	$("#endTime").html('');
	$("#endTime").html(getTimeSelect());
	doFilter();
}

function doFilterPhaseZero(){
	filterPressed=true;
	doFilter();
}

function getRoomFromPlanificationPhaseOne() {
	// sperez: Esto es para que no venga sin nada la grilla
	initRoom();
}
function getRoomFromPlanificationPhaseTwo() {
	var roomFilter = $("#roomFilterContent").html();
	var roomGride = $("#roomsContent").html();
	var roomPopUp = $("#roomPopUp");
	var contentRoomsPlanificationFilter = $("#contentRoomsPlanificationFilter");
	var contentRoomsPlanificationGride = $("#contentRoomsPlanificationGride");
	contentRoomsPlanificationFilter.html("");
	contentRoomsPlanificationGride.html("");
	contentRoomsPlanificationFilter.append(roomFilter);
	contentRoomsPlanificationGride.append(roomGride);
	if(!filterPressed){
		roomPopUp.show("slide", {}, 1000);
	}else{
	    filterPressed=false;
	}
	
	$("#startDay").hide();
	$("#startDay2").show();
	$("#startDay2").datepicker();
	$("#endDay").hide();
	$("#endDay2").show();
	$("#endDay2").datepicker();
	$("#roomToFilter").val("");
	
	if(iAmIn == 1){
		$("#filterStartDay").hide();
		$("#filterEndDay").hide();
		$("#filterShift").show();
		$("#filterSelectDay").show();
	}else{
		$("#filterSelectDay").hide();
		$("#filterShift").hide();
		$("#filterStartDay").show();
		$("#filterEndDay").show();
	}
}

function setAvailables(){
	$("#rbAvYes").trigger("click");
}

$(function() {
	
	selectTurn = $("#selectTurn");
	
	$.getJSON('/enma/shift/getAll/', function(data) {
		var select=selectTurn[0];
	    select.options.length = 0; // limpio turnos existentes
	    select.options.add(new Option('',''));
	    
		if(data.responseCode == 200){
			for(var i = 0; i<data.shifts.length; i++){
				var shift = data.shifts[i];
				select.options.add(new Option(shift.description, shift.id));
			}
			
		}else{
			alert(data.message);
		}
		
	});
	
    
    $( "#filterList li" ).draggable({
      appendTo: "body",
      helper: "clone"
    });
    $( "#myFilterList ul" ).droppable({
      activeClass: "ui-state-default",
      hoverClass: "ui-state-hover",
      accept: ":not(.ui-sortable-helper)",
      drop: function( event, ui ) {
        $( this ).find( ".placeholder" ).remove();
        $( "<li></li>" ).text( ui.draggable.text() ).appendTo( this );
      }
    }).sortable({
      items: "li:not(.placeholder)",
      sort: function() {
        // gets added unintentionally by droppable interacting with sortable
        // using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options
        $( this ).removeClass( "ui-state-default" );
      }
    });
  });